define([
    'static',
    '../../../utils/http',
    '../../../bean/notice',
    '../../../bean/adresource',
    '../../../bean/common',
    '../../../bean/user'
], function(
    CONST,
    http,
    noticeModel,
    adresourceModel,
    commonModel,
    userModel
) {
    extend(Main, Combine);

    function Main() {
        var _this = this;
        var _super = arguments.callee.parent;
        this.init = function() {
            _this._DOM = $("[data-com='alert']");
            _this.render();
            _this.event();
            userModel.queryUser(function(user) {
                _this.userId = user.ticket;
                // _this.openWebSocket();
            });
        };

        this.render = function() {
            noticeModel.queryMessage(function(messages) {
                _this._DOM.find('.badge-notify').text(messages.totalSize);
                _this.handleData(messages);

            });
        }

        this.event = function() {
            _this._DOM.off('click', '.btn-notice,#message-num').on('click', '.btn-notice,#message-num', function(e) {
                e.stopPropagation();
                $('#mess-drop').toggleClass('active');
            });
            //关闭消息
            $('.logo-wrapper,.info-help,.info-login,.fmp-article,#mess-list,.bottom-bar,.status-wrapper').click(function() {
                $('#mess-drop').removeClass('active');
            })
        }

        this.handleData = function(json) {
            var messageNum = $('#message-num'),
                messM = $("#mess-m");
            if (json.totalSize == 0) {
                //没有数据 显示空白页
                messageNum.hide();
                messM.find('h4 small').html(I18N.getText('index','noMsg'));
                messM.css('background-color','#fff').show();
                console.log("没有消息！");
            } else {
                messageNum.text(json.totalSize);
                messageNum.data("num", json.totalSize);
                messM.hide();
                messageNum.show();
                var lastTime = _this.handleMessage(json);
                var htmlTime = I18N.getText('index','lastUpdate') + kit.formatTime(lastTime) + " GMT ";
                if (new Date(lastTime).getTimezoneOffset() / 60 > 0) {
                    htmlTime += "+" + new Date(lastTime).getTimezoneOffset() / 60;
                } else {
                    htmlTime += "+" + new Date(lastTime).getTimezoneOffset() / -60;
                }
                $("#mess-time").html(htmlTime);
            }

            $('#mess-drop .bottom-bar a').html(I18N.getText('index','readAll')+'&nbsp;&nbsp;&nbsp;&gt;');
        }


        this.handleMessage = function(res) {
            var str = "";
            var lastTime = 0;
            var befStr, afterStr = "";
            var subNum = 80; //显示的message body字数
            _this._DOM.find(".list-group ul").html('');
            $.each(res.resultList, function(n, obj) {
                if (n == 0) {
                    lastTime = obj.sendTime;
                }
                str += '<li class="list-group-item" id="' + obj.id + '"><span class="badge-i"><i class="fa fa-times"></i></span>';
                if (obj.needFunctionJump) {
                    str += '<span class="glyphicon glyphicon-exclamation-sign  mess-i"></span>';
                } else {
                    str += '<span class="glyphicon glyphicon-envelope mess-i"></span>';
                }
                if (obj.url == "" || typeof obj.url == "undefined") {
                    str += '<h4 class="mess-head">' + obj.title + '</h4>';
                } else {
                    str += '<h4 class="mess-head">' + obj.title + '</h4>';
                }
                var idpart = obj.url.split("?")[1];
                var redir = obj.url.split("?")[0];
                var imageBathId = (idpart) ? idpart.match(/imageBathId=([a-z0-9]+)/i)[1] : '';
                if (!obj.url) {
                    str += '<p class="mess-body" objid=' + obj.id + '>' + obj.body + '</p>';
                } else {
                    if (imageBathId) {
                        str += '<p class="mess-body">\
                                    <span data-toggle="modal" class="mess-head-a" imageBathId=' + imageBathId + ' href="javascript:;" url=' + obj.url + ' objid=' + obj.id + ' jump=' + redir + '>' + obj.body + '</span></p>';
                    } else if (obj.url == '#!adList') {
                        str += '<p class="mess-body">\
                                <span href="javascript:;"  url=' + obj.url + ' class="mess-head-a">' + obj.body + '</span></p>';
                    } else {
                        str += '<p class="mess-body">\
                                <span data-toggle="modal" data-target="#messageModal" class="mess-head-a"  href="javascript:;" url=' + obj.url + ' objid=' + obj.id + ' jump=' + redir + '>' + obj.body + '</span></p>';
                    }
                }
                // str += '<span class="mess-open" open-status="false">[展开全文]</span>';
                str += '<span class="mess-send-time">' + kit.formatTime(obj.sendTime) + '</span></li>';
            });
            _this._DOM.find(".list-group ul").prepend(str);
            $.each($('.mess-body'), function(i, v) {
                if ($(this).height() >= $('.mess-head-a', this).height()) {
                    $('.mess-open', $(this).closest('.list-group-item')).hide();
                }
            });
            $('#mess-drop .list-group').niceScroll();
            //提醒内容跳转事件
            _this._DOM.find('.list-group .mess-head-a').unbind("click").click(function(e) {
                e.stopPropagation();
                $('#mess-drop').toggleClass('active');
                var id = $(this).closest('.list-group-item').attr('id');
                var href=$(this).closest('.list-group-item').find('.mess-head-a').attr('url');
                if(href&&href.length>0){
                    window.location.hash=href;
                }
                $(this).closest('.list-group-item').remove();
                var params = { id: id };
                _this.reduceMessage(params);
            });
            _this.addMyEventListener(afterStr, subNum);
            return lastTime;
        }


        this.addMyEventListener = function(afterStr, subNum) {
            _this._DOM.find(".list-group").find(".mess-open").unbind("click");
            _this._DOM.find(".list-group").find(".list-group-item").find(".badge-i").unbind("click");

            _this._DOM.find(".list-group").find(".mess-open").bind("click", function() {
                var openStatus = this.getAttribute('open-status'),
                    forContent = $('.mess-body', $(this).closest('.list-group-item'));
                if (openStatus == 'true') {
                    forContent.removeClass('show-all');
                } else {
                    forContent.addClass('show-all');
                }
            });
            _this._DOM.find(".list-group").find(".list-group-item").find(".badge-i").bind("click", function() {
                _this.clickTitle($(this).closest("li"));
            });
        }


        this.initMessageModal = function(da) {
            var _this = this;
            var the = $("body>div.modal.common-modal");
            var box = $('<div class="row"></div>');
            console.log(da)
            for (var i = 0; i < da.length; i++) {
                var o = da[i];
                var app = o.appNames; //应用
                var langs = $.isArray(o.languages) ? o.languages.join(',') : ''; //语言
                var gender = (o.gender == 1 ? "男" : (o.gender == 2 ? "女" : "全部")); //性别
                var txt = '<div class="col-sm-6">\
                        <div class="thumbnail pull-left">\
                            <img style="max-height:100px;max-width:120px" class="superbox-img" src="' + o.litImgURL + '">\
                        </div>\
                    <ul class="messageModal-desc">\
                        <li>应用：<span title="' + (app.join(" ")) + '">' + (app.join(" ")) + '</span> </li>\
                        <li>语言：<span >' + langs + '</span> </li>\
                        <li>性别：<span>' + gender + '</span>\
                        </li>\
                    </ul></div>';
                box.append(txt);
            }
            the.empty().dialog({
                id: "messageModal",
                title: "图片详情",
                body: box
            }).modal();
        }

        this.reduceMessage = function(params) {
            noticeModel.updateMessage(params, function(result) {
                if (result == 1) {
                    // if (result == 1) { //使用这个......
                    //更新成功！
                    var num = ($('#message-num').text() * 1) - 1;
                    if (num == 0) {
                        $('#message-num').hide();
                        $("#mess-m").show();
                        $("#mess-time").html("");
                    } else {
                        $('#message-num').text(num);
                    }
                } else {
                    console.log("更新失败！返回值为：" + result.data);
                }
            });
        }


        this.clickTitle = function(obj) {
            var _this = this;
            $(obj).remove();
            var id = $(obj).attr("id");
            _this.reduceMessage({
                id: id
            });
        }


        this.openWebSocket = function() {
            var _this = this;
            commonModel.getConfigInfo(function(res) {
                var json = typeof(res) == 'string' ? JSON.parse(res) : res;
                if (json.flag == 'fail') {
                    console.log("websocket 连接信息没有从配置中心获取到。");
                    return;
                }
                var websocket_url = res.url;
                var websocket_time = res.heartTime;
                //打开websocket
                if (!websocket_url) {
                    return;
                }
                var wsServer = websocket_url;
                var websocket = new WebSocket(wsServer);
                websocket.onopen = function(evnt) {
                    websocket.send("userId:" + _this.userId);
                    //心跳测试
                    setInterval(function() {
                        try {
                            websocket.send("test");
                        } catch (e) {
                            console.error(e);
                            console.error('socket closed!reconnect!');
                            _this.openWebSocket();
                        }
                    }, websocket_time);
                };
                websocket.onmessage = function(evnt) {
                    //接受数量
                    var json = JSON.parse(evnt.data);
                    if (json.flag != null) {
                        return;
                    }
                    _this.handleData(json);
                };
                websocket.onerror = function(evnt) {
                    console.log("websocket 异常：" + evnt.data);
                };
                websocket.onclose = function(evnt) {
                    console.log('Disconnecting connection');
                };
            });

        }



    }
    return new Main();
});
